"""
本文件查看c中build是否覆盖全部文件,并使用BUILD.gn生成映射关系
本文件检查interface映射文件是否覆盖全部文件
"""

import os
import json

def find_build_gn_directories(root_path):
    build_gn_directories = []
    for root, dirs, files in os.walk(root_path):
        for file in files:
            if file == "BUILD.gn":
                build_gn_directories.append(root)
    build_gn_directories.sort()
    return build_gn_directories

def is_parent_path_in_linux(parent_path, child_path):
    parent_parts = parent_path.split("/")
    child_parts = child_path.split("/")
    if len(parent_parts) > len(child_parts):
        return False
    for i in range(len(parent_parts)):
        if parent_parts[i]!= child_parts[i]:
            return False
    return True

def change_linux_path(all_build_path):
    new_path_list = []
    for path in all_build_path:
        new_path_list.append(path.replace('..\\interface_sdk_c-master', 'interface/sdk_c').replace('\\', '/'))
    return new_path_list



def json_to_path_map(json_file_path):
    result_map = {}
    with open(json_file_path, 'r') as file:
        data = json.load(file)
        for item in data:
            path_value = item["path"]
            result_map[path_value] = item
    return result_map

def generate_new_reflection_list(all_build_path, old_compare_map):
    new_list = []
    for path in all_build_path:
        bundle_set = set()
        path_set = set()
        for key in old_compare_map:
            if is_parent_path_in_linux(path, key):
                bundle_set = bundle_set.union(set(old_compare_map[key]['bundle_name']))
                path_set = path_set.union(set(old_compare_map[key]['build_targets']))
                print(bundle_set)
        new_list.append({
            "path": path,
            "bundle_name": list(bundle_set),
            "build_targets": list(path_set)
        })
    return new_list

def write_json(json_data, json_path):
    with open(json_path, 'w') as file:
        json.dump(json_data, file, indent=4)

def run(interface_path,old_json_path):
    # 获取interface_path 仓下全部 BUILD.gn所属目录列表,并排序
    all_build_path = find_build_gn_directories(interface_path)
    linux_all_build_path = change_linux_path(all_build_path)
    # print(linux_all_build_path)
    # 从老映射表中获取映射内容
    old_compare_map = json_to_path_map(old_json_path)
    reflection_list = generate_new_reflection_list(linux_all_build_path, old_compare_map)
    # print(reflection_list)
    write_json(reflection_list, "new_c_api_bak.json")

def check_covered_files(interface_path, build_paths):
    all_api_files = []
    # 遍历给定路径下所有文件，获取其绝对路径并添加到all_files列表
    for root, dirs, files in os.walk(interface_path):
        for file in files:
            file_path = os.path.join(root, file)
            all_api_files.append(file_path.replace('..\\interface_sdk_c-master', 'interface/sdk_c').replace('\\', '/'))
    all_api_files.sort()
    build_paths.sort()
    uncovered_files = []
    count_api_files = 0
    count_build_path = 0
    while count_api_files < len(all_api_files):
        file_path =  all_api_files[count_api_files]
        if ".gitee" in file_path:
            count_api_files += 1
            continue
        comapre_flag = False
        current_build_path = count_build_path
        while current_build_path < len(build_paths):
            build_path = build_paths[current_build_path]
            if is_parent_path_in_linux(build_path, file_path):
                comapre_flag = True
                count_build_path = current_build_path
                break
            current_build_path += 1
        if not comapre_flag:
            uncovered_files.append(all_api_files[count_api_files])
        count_api_files += 1
    return uncovered_files

def find_parent_child_directories(path_list):
    parent_child_pairs = []
    for i in range(len(path_list)):
        for j in range(len(path_list)):
            if i!= j:
                parent_path = path_list[i]
                child_path = path_list[j]
                if child_path.startswith(parent_path + "/"):
                    parent_child_pairs.append((parent_path, child_path))
                elif parent_path.startswith(child_path + "/"):
                    parent_child_pairs.append((child_path, parent_path))
    return parent_child_pairs

# 检查是否有文件列表中无法覆盖
def check(interface_path,new_json_path):
    # newpath中获取全部path列表
    new_paths = list(json_to_path_map(new_json_path).keys())
    # 检查是否有父子关系
    parent_child_pairs = find_parent_child_directories(new_paths)
    print(parent_child_pairs)
    # 检查是否覆盖全
    uncovered_files = check_covered_files(interface_path, new_paths)
    write_json(uncovered_files,"./uncovered_files.json")


if __name__ == '__main__':
    # run("..\\interface_sdk_c-master", "old_api.json")
    check("..\\interface_sdk_c-master", "new_c_api_bak.json")